//
//  UITextView + Extension.swift
//  emojeTest
//
//  Created by juxiaohui on 16/11/3.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit

extension UITextView {
    
     /// 获取textView上的属性字符串
    
    func getEmoticonString() -> String {
        
        let attMStr = NSMutableAttributedString.init(attributedString: attributedText)
        
        let range = NSRange.init(location: 0, length: attMStr.length)
        
        attMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            
            if let attacment = dict["NSAttachment"] as? JXHTextAttachment {//是一个表情
                attMStr.replaceCharacters(in: range, with: attacment.chs!)
            }
        }
        
        return attMStr.string
    }
    
    
    ///插入表情
    func insertEmoticon(emoticon : JXHEmoticon) {
        //空白表情
        if emoticon.isEmpty {
            return
        }
        if emoticon.isRemove {//删除按钮
            deleteBackward()//删除前面一个字符
            return
        }
        //emoji表情
        if emoticon.emojiCode != nil { //是emoji表情
            
            let textRange = selectedTextRange!
            replace(textRange, withText: emoticon.emojiCode!)
            return
        }
        //普通表情 图文混排
        //根据图片路径创建属性字符串
        let attacment = JXHTextAttachment.init()
        attacment.chs = emoticon.chs
        let font = self.font
        attacment.bounds = CGRect.init(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
        attacment.image = UIImage.init(contentsOfFile: emoticon.pngPath!)
        let attImageStr = NSAttributedString.init(attachment: attacment)
        //创建可变的属性字符串
        let attMStr = NSMutableAttributedString.init(attributedString: attributedText)
        
        let textRange = selectedRange
        
        attMStr.replaceCharacters(in: textRange, with: attImageStr)
        attributedText = attMStr
        
        //重置字体
        self.font = font
        //将光标设置为远了的位置+1
        
        selectedRange = NSRange.init(location: textRange.location + 1, length: 0)
    }
}
